﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SeaBattle.UI.Web.Models;
using SeaBattle.Domain.Abstract;
using SeaBattle.Domain.Abstract.Services;

namespace SeaBattle.UI.Web.Controllers
{    
    public class RegisterController : Controller
    {
        private IPlayerRepository playerRepository;
        private IAccountService accountService;
        public RegisterController(IPlayerRepository playerRepository, IAccountService accountService)
        {
            this.playerRepository = playerRepository;
            this.accountService = accountService;
        }
        //
        // GET: /Register/

        public ActionResult Index()
        {
            return View(new RegistrationModel()) ;
        }

        [HttpPost]
        public ActionResult Index(RegistrationModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.Password == model.ConfirmPassword)
                {
                    var players = playerRepository.Players;
                    if (players.FirstOrDefault(x => x.Login == model.Login) == null)
                    {
                        var player = playerRepository.CreateNewPlayer(model.Name, model.Login,model.Password);
                        playerRepository.SavePlayer(player);
                        accountService.SetPlayerBalance(player, accountService.DefaultBalance);                        
                        return RedirectToAction("LogOn", "Home");
                    }
                    else
                        ModelState.AddModelError("", "This login is exists");
                }
                else
                    ModelState.AddModelError("","Passwords are not equal");
            }
            return View(model);
        }
    }
}
